<template>
  <view class="w-full max-w-[750rpx] mx-auto bg-white">
    <!-- 输入弹窗 -->
    <nut-popup v-model:visible="showInputPopup" position="center" round>
      <view class="w-[600rpx] p-[40rpx] bg-white rounded-[20rpx] shadow-2xl border border-gray-100">
        <view class="text-center mb-[30rpx]">
          <text class="text-[32rpx] font-bold text-gray-800">{{ popupTitle }}</text>
        </view>

        <!-- 编辑模式输入框 -->
        <view v-if="!isAddMode" class="mb-[30rpx]">
          <input
            v-model="inputValue"
            :placeholder="placeholderText"
            class="w-full box-border px-[30rpx] py-[20rpx] border-2 border-blue-300 rounded-[16rpx] text-[32rpx] bg-gray-50 focus:border-blue-500 focus:bg-white transition-all duration-300 placeholder-gray-400"
            type="text"
            placeholder-style="color: #9CA3AF; font-size: 28rpx;"
          />
        </view>

        <!-- 添加模式输入框 -->
        <view v-if="isAddMode" class="mb-[30rpx]">
          <view class="mb-[20rpx]">
            <text class="text-[24rpx] text-gray-600 mb-[8rpx] block">项目名称</text>
            <input
              v-model="newItemName"
              placeholder="请输入项目名称"
              class="w-full box-border px-[30rpx] py-[20rpx] border-2 border-blue-300 rounded-[16rpx] text-[32rpx] bg-gray-50 focus:border-blue-500 focus:bg-white transition-all duration-300 placeholder-gray-400"
              type="text"
              placeholder-style="color: #9CA3AF; font-size: 28rpx;"
            />
          </view>
          <view class="mb-[20rpx]">
            <text class="text-[24rpx] text-gray-600 mb-[8rpx] block">物联网数据</text>
            <input
              v-model="newItemIotValue"
              placeholder="请输入物联网数据"
              class="w-full box-border px-[30rpx] py-[20rpx] border-2 border-blue-300 rounded-[16rpx] text-[32rpx] bg-gray-50 focus:border-blue-500 focus:bg-white transition-all duration-300 placeholder-gray-400"
              type="text"
              placeholder-style="color: #9CA3AF; font-size: 28rpx;"
            />
          </view>
          <view>
            <text class="text-[24rpx] text-gray-600 mb-[8rpx] block">手动录入</text>
            <input
              v-model="newItemManualValue"
              placeholder="请输入手动录入数据"
              class="w-full box-border px-[30rpx] py-[20rpx] border-2 border-blue-300 rounded-[16rpx] text-[32rpx] bg-gray-50 focus:border-blue-500 focus:bg-white transition-all duration-300 placeholder-gray-400"
              type="text"
              placeholder-style="color: #9CA3AF; font-size: 28rpx;"
            />
          </view>
        </view>

        <view class="flex justify-between gap-[24rpx]">
          <nut-button type="default" size="large" class="flex-1 h-[80rpx] rounded-[12rpx] text-[28rpx] font-medium border-2 border-gray-300 hover:border-gray-400" @click="cancelInput">
            取消
          </nut-button>
          <nut-button type="success" size="large" class="flex-1 h-[80rpx] rounded-[12rpx] text-[28rpx] font-medium bg-blue-500 hover:bg-blue-600" @click="confirmInput"> 确定 </nut-button>
        </view>
      </view>
    </nut-popup>


    <!-- 头部 -->
    <view class="flex items-center justify-between p-[30rpx] border-b border-gray-100">
      <text class="text-[32rpx] font-bold text-gray-800">常规项目</text>
      <view class="flex items-center" @click="toggleExpand">
        <IconFont 
          :name="isExpanded ? 'arrow-up' : 'arrow-down'" 
          size="10" 
          color="#27c530" 
          :class="['transition-transform duration-200', isExpanded ? 'rotate-180' : 'rotate-0']"
        />
      </view>
    </view>

    <!-- 健康指标列表 -->
    <view v-if="isExpanded" class="px-[30rpx] py-[20rpx]">
      <!-- 固定健康项目 - 不能删除 -->
      <view v-for="(item, index) in fixedHealthItems" :key="`fixed-${index}`" class="flex items-start py-[30rpx] px-[20rpx] border-b border-gray-100 last:border-b-0 bg-white rounded-[12rpx] mb-[8rpx] shadow-sm">
        <!-- 图标 -->
        <view class="w-[60rpx] h-[60rpx] rounded-full bg-green-500 flex items-center justify-center mr-[25rpx] mt-[8rpx] flex-shrink-0">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="-yiliao1" size="20" color="#fff" />
        </view>

        <!-- 内容区域 -->
        <view class="flex-1">
          <!-- 项目名称 -->
          <view class="mb-[12rpx] flex items-center">
            <text class="text-[30rpx] font-medium text-gray-800">{{ item.name }}</text>
            <view class="px-[8rpx] py-[4rpx] ml-2" :class="getStatusClass(item.status)">
              <text class="text-[18rpx] font-medium">{{ item.statusText }}</text>
            </view>
          </view>

          <!-- 两列数据显示 -->
          <view class="flex items-start justify-between">
            <!-- 物联网数据 -->
            <view class="flex flex-col items-start flex-1 mr-[40rpx]">
              <text class="text-[22rpx] text-[#ccc] mb-[8rpx] font-medium">物联网数据</text>
              <text class="text-[32rpx] font-bold text-[#333]">{{ item.iotValue || "-" }}</text>
            </view>

            <!-- 手动录入 -->
            <view class="flex flex-col items-end flex-1 p-[8rpx] rounded-[8rpx] active:bg-gray-50" @click="showInputDialog(item, `fixed-${index}`)">
              <text class="text-[22rpx] text-[#ccc] mb-[8rpx] font-medium flex items-center">
                手动录入
                <IconFont name="edit" size="12" class="ml-2" />
              </text>
              <text class="text-[32rpx] font-bold text-[#333]">{{ item.manualValue }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 动态健康项目 -->
      <view v-for="(item, index) in healthMetrics" :key="`dynamic-${index}`" class="flex items-start py-[30rpx] px-[20rpx] border-b border-gray-100 last:border-b-0 bg-white rounded-[12rpx] mb-[8rpx] shadow-sm">
        <!-- 图标 -->
        <view class="w-[60rpx] h-[60rpx] rounded-full bg-green-500 flex items-center justify-center mr-[25rpx] mt-[8rpx] flex-shrink-0">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="-yiliao1" size="20" color="#fff" />
        </view>

        <!-- 内容区域 -->
        <view class="flex-1">
          <!-- 项目名称 -->
          <view class="mb-[12rpx] flex items-center">
            <text class="text-[30rpx] font-medium text-gray-800">{{ item.name }}</text>
            <view class="px-[8rpx] py-[4rpx] ml-2" :class="getStatusClass(item.status)">
              <text class="text-[18rpx] font-medium">{{ item.statusText }}</text>
            </view>
          </view>

          <!-- 两列数据显示 -->
          <view class="flex items-start justify-between">
            <!-- 物联网数据 -->
            <view class="flex flex-col items-start flex-1 mr-[40rpx]">
              <text class="text-[22rpx] text-[#ccc] mb-[8rpx] font-medium">物联网数据</text>
              <text class="text-[32rpx] font-bold text-[#333]">{{ item.iotValue || "-" }}</text>
            </view>

            <!-- 手动录入 -->
            <view class="flex flex-col items-end flex-1 p-[8rpx] rounded-[8rpx] active:bg-gray-50" @click="showInputDialog(item, `dynamic-${index}`)">
              <text class="text-[22rpx] text-[#ccc] mb-[8rpx] font-medium flex items-center">
                手动录入
                <IconFont name="edit" size="12" class="ml-2" />
              </text>
              <text class="text-[32rpx] font-bold text-[#333]">{{ item.manualValue }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 自定义项目列表 -->
      <view
        v-for="(item, index) in newItems"
        :key="`new-${index}`"
        class="flex items-start py-[20rpx] px-[20rpx] border-b border-gray-100 last:border-b-0 bg-white rounded-[12rpx] mb-[8rpx] shadow-sm"
      >
        <!-- 图标 -->
        <view class="w-[60rpx] h-[60rpx] rounded-full bg-blue-500 flex items-center justify-center mr-[25rpx] mt-[8rpx] flex-shrink-0">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="yiliao3" size="20" color="#fff" />
        </view>

        <!-- 内容区域 -->
        <view class="flex-1">
          <!-- 项目名称 -->
          <view class="mb-[12rpx] flex items-center">
            <text class="text-[30rpx] font-medium text-gray-800">{{ item.name }}</text>
            <view class="px-[8rpx] py-[4rpx] ml-2" :class="getStatusClass(item.status)">
              <text class="text-[18rpx] font-medium">{{ item.statusText }}</text>
            </view>
          </view>

          <!-- 两列数据显示 -->
          <view class="flex items-start justify-between">
            <!-- 物联网数据 -->
            <view class="flex flex-col items-start flex-1 mr-[40rpx]">
              <text class="text-[22rpx] text-[#ccc] mb-[8rpx] font-medium">物联网数据</text>
              <text class="text-[32rpx] font-bold text-[#333]">{{ item.iotValue || "-" }}</text>
            </view>

            <!-- 手动录入 -->
            <view class="flex flex-col items-end flex-1 p-[8rpx] rounded-[8rpx] active:bg-gray-50" @click="showInputDialog(item, `new-${index}`)">
              <text class="text-[22rpx] text-[#ccc] mb-[8rpx] font-medium flex items-center">
                手动录入
                <IconFont name="edit" size="12" class="ml-2" />
              </text>
              <text class="text-[32rpx] font-bold text-[#333]">{{ item.manualValue }}</text>
            </view>
          </view>
        </view>

        <!-- 删除按钮 -->
        <view class="ml-[15rpx] mt-[8rpx]" @click="deleteNewItem(index)">
          <view class="w-[40rpx] h-[40rpx] rounded-full flex items-center justify-center active:bg-red-200">
            <IconFont name="close" size="12" color="#ef4444" />
          </view>
        </view>
      </view>

      <view class="flex items-center justify-center p-[20rpx] rounded-[12rpx] border-2 border-dashed border-green-300 active:bg-green-50" @click="showAddDialog" @tap="showAddDialog">
        <IconFont name="plus" size="24" color="#00b26a" />
        <text class="text-[24rpx] text-[#00b26a] ml-[8rpx]">添加自定义项目</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import Taro from "@tarojs/taro";
import { request } from "@/service/request";
import { localStg } from "@/utils";
import { useDemographicInfoStore } from "@/store";
// import { getHealthNurses } from "@/service/api/nurse_nurses";

// 类型定义
interface HealthMetric {
  name: string;
  icon?: string;
  iotValue: string;
  manualValue: string;
  status: string;
  statusText: string;
}

interface CustomHealthItem extends HealthMetric {
  id?: string;
  recordid?: string;
  createTime?: string;
  updateTime?: string;
}


// 获取 store 实例
const demographicStore = useDemographicInfoStore();

// 展开/收起状态
const isExpanded = ref(true);

// 输入弹窗相关状态
const showInputPopup = ref(false);
const inputValue = ref("");
const popupTitle = ref("");
const placeholderText = ref("");
const currentEditIndex = ref(-1);

// 添加模式相关状态
const isAddMode = ref(false);
const newItemName = ref("");
const newItemIotValue = ref("");
const newItemManualValue = ref("");

// 自定义项目数据
const newItems = reactive<CustomHealthItem[]>([]);

// 缓存键名
const CACHE_KEY = 'healthMetricsCache';

// 健康管家相关状态 - 从 store 获取
// const currentManager = computed(() => demographicStore.currentHealthButler);
// const managerList = ref<HealthManager[]>([]);
// const showManagerPopup = ref(false);

// 固定健康指标数据 - 不能删除
const fixedHealthItems = reactive<HealthMetric[]>([
  {
    name: "血压心率",
    icon: "heart",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "血氧",
    icon: "droplet",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "血糖",
    icon: "droplet",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "体温",
    icon: "thermometer",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "血脂",
    icon: "droplet",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "尿酸",
    icon: "droplet",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "睡眠评分",
    icon: "moon",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "BMI",
    icon: "chart-line",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "体重",
    icon: "scale",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
  {
    name: "运动其他",
    icon: "running",
    iotValue: "",
    manualValue: "",
    status: "normal",
    statusText: "正常",
  },
]);

// 健康指标数据
const healthMetrics = reactive<HealthMetric[]>([
]);

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 点击手动录入弹出输入框
const showInputDialog = (item: HealthMetric | CustomHealthItem, index: number | string) => {
  console.log("showInputDialog 被调用", { item: item.name, index, manualValue: item.manualValue });
  isAddMode.value = false;
  popupTitle.value = `修改${item.name}`;
  placeholderText.value = `请输入${item.name}数值`;
  // 使用 nextTick 确保数据正确显示
  nextTick(() => {
    inputValue.value = item.manualValue || ""; // 设置当前值作为默认值
    currentEditIndex.value = index as any;
    showInputPopup.value = true;
    console.log("编辑模式设置完成", { isAddMode: isAddMode.value, inputValue: inputValue.value });
  });
};

// 显示添加自定义项目弹窗
const showAddDialog = () => {
  console.log("showAddDialog 被调用");
  isAddMode.value = true;
  popupTitle.value = "添加自定义项目";
  // 使用 nextTick 确保数据正确重置
  nextTick(() => {
    newItemName.value = "";
    newItemIotValue.value = "";
    newItemManualValue.value = "";
    currentEditIndex.value = -1;
    showInputPopup.value = true;
    console.log("弹窗状态设置完成", { isAddMode: isAddMode.value, showInputPopup: showInputPopup.value });
  });
};

// 取消输入
const cancelInput = () => {
  console.log("cancelInput 被调用");
  showInputPopup.value = false;
  inputValue.value = "";
  newItemName.value = "";
  newItemIotValue.value = "";
  newItemManualValue.value = "";
  currentEditIndex.value = -1;
  isAddMode.value = false;
  console.log("取消操作完成", { isAddMode: isAddMode.value, showInputPopup: showInputPopup.value });
};

// 确认输入
const confirmInput = async () => {
  console.log("confirmInput 被调用", { isAddMode: isAddMode.value });
  Taro.showToast({ title: "确定按钮被点击", icon: "none", duration: 1000 });
  try {
  if (isAddMode.value === true) {
    // 添加模式
    console.log("进入添加模式", {
      name: newItemName.value,
      iotValue: newItemIotValue.value,
      manualValue: newItemManualValue.value
    });
    
    if (!newItemName.value.trim() || !newItemIotValue.value.trim() || !newItemManualValue.value.trim()) {
      console.log("验证失败：信息不完整");
      Taro.showToast({
        title: "请填写完整信息",
        icon: "none",
        duration: 1500,
      });
      return;
    }

    // 调用接口添加新项目
    try {
      const obj = localStg.get("demographicInfo");
      console.log("获取到的 demographicInfo:", obj);
      
      if (!obj || !obj.recordid || !obj.idNumber) {
        console.log("demographicInfo 数据不完整:", obj);
        Taro.showToast({
          title: "用户信息不完整，请重新登录",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      
      const submitData = {
        proName: "常规项目", // 项目大类名称
        subName: newItemName.value.trim(), // 项目子类名称（自定义项目名称）
        subValue: 10, // 项目子类码值，固定为10
        subRes: `${newItemIotValue.value.trim()}/${newItemManualValue.value.trim()}`, // 项目检查结果值，物联网数据/手动录入数据
        updateTime: new Date().toISOString().split("T")[0],
        recordid: obj.recordid,
        idNumber: obj.idNumber,
      };

      console.log("提交自定义项目数据:", submitData);

      // 调用接口
      console.log("开始发送网络请求...");
      const { error, success } = await request.post("/health_records/health_basepro/healthBaseProjectInfo/add", submitData, {
        useErrMsg: true,
      });
      console.log("网络请求完成", { error, success });

      if (!error && success) {
        // 接口调用成功后，添加到本地显示
        newItems.push({
          name: newItemName.value.trim(),
          icon: "yiliao3",
          iotValue: newItemIotValue.value.trim(),
          manualValue: newItemManualValue.value.trim(),
          status: "normal",
          statusText: "正常",
        });

        Taro.showToast({
          title: "添加成功",
          icon: "success",
          duration: 1500,
        });
        getList();
        closePopup();
      } else {
        Taro.showToast({
          title: "添加失败",
          icon: "none",
          duration: 1500,
        });
        closePopup();
      }
    } catch (error) {
      console.error("添加自定义项目失败:", error);
      Taro.showToast({
        title: "添加失败",
        icon: "none",
        duration: 1500,
      });
      closePopup();
    }
  } else {
    // 编辑模式
    if (!inputValue.value.trim()) {
      Taro.showToast({
        title: "请输入有效数值",
        icon: "none",
        duration: 1500,
      });
      closePopup();
      return;
    }

    const indexStr = String(currentEditIndex.value);
    if (indexStr && indexStr.startsWith("fixed-")) {
        // 更新固定项目 - 只更新本地数据，不调用API
        const index = parseInt(indexStr.replace("fixed-", ""));
        if (index >= 0 && index < fixedHealthItems.length) {
          updateFixedManual(index, inputValue.value.trim());
          Taro.showToast({
            title: "修改成功",
            icon: "success",
            duration: 1500,
          });
          closePopup();
        }
    } else if (indexStr && indexStr.startsWith("new-")) {
        // 更新自定义项目
        const index = parseInt(indexStr.replace("new-", ""));
        const item = newItems[index];

        if (item && item.id) {
          try {
            // 调用更新接口
            const obj = localStg.get("demographicInfo");
            const updateData = {
              id: item.id,
              proName: "常规项目",
              subName: item.name,
              subValue: 10,
              subRes: inputValue.value.trim(),
              updateTime: new Date().toISOString().split("T")[0],
              recordid: obj.recordid,
              idNumber: obj.idNumber,
            };

            const { error, success } = await request.put("/health_records/health_basepro/healthBaseProjectInfo/edit", updateData, {
              useErrMsg: true,
            });

            if (!error && success) {
              // 更新本地数据
              updateNewItemManual(index, inputValue.value.trim());
              Taro.showToast({
                title: "修改成功",
                icon: "success",
                duration: 1500,
              });
              // 重新获取数据列表
              getList();
              closePopup();
            } else {
              Taro.showToast({
                title: "修改失败",
                icon: "none",
                duration: 1500,
              });
              closePopup();
            }
          } catch (error) {
            console.error("更新项目失败:", error);
            Taro.showToast({
              title: "修改失败",
              icon: "none",
              duration: 1500,
            });
            closePopup();
          }
        } else {
          // 如果没有ID，直接更新本地数据
          updateNewItemManual(index, inputValue.value.trim());
          Taro.showToast({
            title: "修改成功",
            icon: "success",
            duration: 1500,
          });
          closePopup();
        }
    } else if (indexStr && indexStr.startsWith("dynamic-")) {
        // 更新动态项目
        const index = parseInt(indexStr.replace("dynamic-", ""));
        if (index >= 0 && index < healthMetrics.length) {
          updateDynamicManual(index, inputValue.value.trim());
          Taro.showToast({
            title: "修改成功",
            icon: "success",
            duration: 1500,
          });
          closePopup();
        }
    } else if (typeof currentEditIndex.value === 'number' && currentEditIndex.value >= 0) {
        const index = currentEditIndex.value as number;
        if (index >= 0 && index < healthMetrics.length) {
          updateDynamicManual(index, inputValue.value.trim());
          Taro.showToast({
            title: "修改成功",
            icon: "success",
            duration: 1500,
          });
          closePopup();
        }
    }
  }
  } finally {
    // 兜底关闭，避免任何异常导致弹窗不关闭
    showInputPopup.value = false;
  }

  // 关闭弹窗并重置状态
  closePopup();
};

// 删除自定义项目
const deleteNewItem = async (index: number) => {
  Taro.showModal({
    title: "确认删除",
    content: "确定要删除这个自定义项目吗？",
    success: async (res) => {
      if (res.confirm) {
        const item = newItems[index];
        if (item && item.id) {
          try {
            // 调用删除接口
            const { error, success } = await request.delete(
              `/health_records/health_basepro/healthBaseProjectInfo/delete?id=${item.id}`,
              {},
              {
                useErrMsg: true,
              }
            );

            if (!error && success) {
              Taro.showToast({
                title: "删除成功",
                icon: "success",
                duration: 1500,
              });
              // 重新获取数据列表
              getList();
            } else {
              Taro.showToast({
                title: "删除失败",
                icon: "none",
                duration: 1500,
              });
            }
          } catch (error) {
            console.error("删除项目失败:", error);
            Taro.showToast({
              title: "删除失败",
              icon: "none",
              duration: 1500,
            });
          }
        } else {
          // 如果没有ID，直接从本地数组移除（可能是本地添加但未保存的项目）
          newItems.splice(index, 1);
          Taro.showToast({
            title: "删除成功",
            icon: "success",
            duration: 1500,
          });
          // 自动保存缓存
          saveCache();
        }
      }
    },
  });
};

const getList = async () => {
  const obj = localStg.get("demographicInfo");
  const { success } = await request.get(
    "https://anfine.huasun-healthcare.com/api/health_records/health_basepro/healthBaseProjectInfo/list",
    {
      // recordID: obj.recordid,
      idNumber: obj.idNumber,
    },
    {
      useErrMsg: true,
    }
  );
  console.log("getList", success);
  const list = success.records || [
    {
      id: "1967593351292788737",
      recordid: 100000000010000060,
      name: null,
      idNumber: "452225198403150039",
      proName: "常规项目",
      subName: "血压·心率",
      subValue: 10,
      subRes: "123",
      detail: null,
      createBy: null,
      createTime: "2025-09-15",
      updateBy: null,
      updateTime: "2025-09-15",
      note: null,
      valid: null,
      seeId: null,
      seeDate: null,
    },
  ];

  // 处理接口数据，转换为页面显示格式
  processHealthData(list);
  
  // 处理完接口数据后，合并缓存中的手动录入数据
  const cachedData = localStg.get(CACHE_KEY as any) as any;
  if (cachedData) {
    // 合并缓存中的手动录入数据到接口数据
    if (cachedData.newItems && Array.isArray(cachedData.newItems)) {
      cachedData.newItems.forEach((cachedItem: any) => {
        const existingItem = newItems.find(item => item.id === cachedItem.id || item.name === cachedItem.name);
        if (existingItem && cachedItem.manualValue) {
          existingItem.manualValue = cachedItem.manualValue;
        }
      });
    }
    // 合并固定项目和动态项目的手动录入数据
    if (cachedData.fixedHealthItems && Array.isArray(cachedData.fixedHealthItems)) {
      cachedData.fixedHealthItems.forEach((it: any, idx: number) => {
        if (fixedHealthItems[idx] && it.manualValue) {
          fixedHealthItems[idx].manualValue = it.manualValue;
        }
      });
    }
    if (cachedData.healthMetrics && Array.isArray(cachedData.healthMetrics)) {
      cachedData.healthMetrics.forEach((it: any, idx: number) => {
        if (healthMetrics[idx] && it.manualValue) {
          healthMetrics[idx].manualValue = it.manualValue;
        }
      });
    }
  }
  
  // 保存合并后的数据
  saveCache();
};

// 处理健康数据，将接口数据转换为页面显示格式
const processHealthData = (list: any[]) => {
  // 清空现有数据
  newItems.splice(0, newItems.length);

  // 处理接口返回的数据
  list.forEach((item: any) => {
    // 解析 subRes 数据（格式：物联网数据/手动录入数据 或 单个数值）
    let iotValue = "";
    let manualValue = "";

    if (item.subRes && item.subRes.includes("/")) {
      const parts = item.subRes.split("/");
      iotValue = parts[0] || "";
      manualValue = parts[1] || "";
    } else {
      // 如果没有分隔符，将数据作为手动录入值
      manualValue = item.subRes || "";
      iotValue = ""; // 物联网数据为空
    }

    // 添加到自定义项目列表
    newItems.push({
      id: item.id, // 保存原始ID用于后续操作
      name: item.subName || "未知项目",
      icon: "yiliao3",
      iotValue: iotValue,
      manualValue: manualValue,
      status: "normal",
      statusText: "正常",
      recordid: item.recordid,
      createTime: item.createTime,
      updateTime: item.updateTime,
    });
  });

  console.log("处理后的健康数据:", newItems);
};

// 保存缓存
function saveCache() {
  try {
    const data = {
      fixedHealthItems: JSON.parse(JSON.stringify(fixedHealthItems)),
      healthMetrics: JSON.parse(JSON.stringify(healthMetrics)),
      newItems: JSON.parse(JSON.stringify(newItems))
    };
    localStg.set(CACHE_KEY as any, data as any);
    console.log('✅ 健康指标数据已保存到缓存');
  } catch (error) {
    console.error('❌ 保存缓存失败:', error);
  }
}

// 加载缓存
function loadCache() {
  try {
    const data = localStg.get(CACHE_KEY as any) as any;
    if (data) {
      mergeCacheIntoState(data);
      console.log('✅ 健康指标数据已从缓存加载');
    }
  } catch (error) {
    console.error('❌ 加载缓存失败:', error);
  }
}

// 合并缓存数据到状态
function mergeCacheIntoState(data: any) {
  if (data?.fixedHealthItems && Array.isArray(data.fixedHealthItems)) {
    data.fixedHealthItems.forEach((it: any, idx: number) => {
      if (fixedHealthItems[idx]) {
        fixedHealthItems[idx].manualValue = it.manualValue || fixedHealthItems[idx].manualValue;
        fixedHealthItems[idx].iotValue = it.iotValue || fixedHealthItems[idx].iotValue;
      }
    });
  }
  if (data?.healthMetrics && Array.isArray(data.healthMetrics)) {
    healthMetrics.splice(0, healthMetrics.length, ...data.healthMetrics);
  }
  // 注意：newItems 会在 getList 中从接口获取，所以这里不直接覆盖
  // 但可以合并手动录入的数据
  if (data?.newItems && Array.isArray(data.newItems)) {
    // 合并缓存中的手动录入数据到接口数据
    data.newItems.forEach((cachedItem: any) => {
      const existingItem = newItems.find(item => item.id === cachedItem.id || item.name === cachedItem.name);
      if (existingItem) {
        existingItem.manualValue = cachedItem.manualValue || existingItem.manualValue;
        existingItem.iotValue = cachedItem.iotValue || existingItem.iotValue;
      }
    });
  }
}

// 使用 splice 方式更新，确保渲染触发
function updateFixedManual(index: number, value: string) {
  if (index >= 0 && index < fixedHealthItems.length) {
    const old = fixedHealthItems[index];
    fixedHealthItems.splice(index, 1, { ...old, manualValue: value });
    // 自动保存缓存
    saveCache();
  }
}

function updateDynamicManual(index: number, value: string) {
  if (index >= 0 && index < healthMetrics.length) {
    const old = healthMetrics[index];
    healthMetrics.splice(index, 1, { ...old, manualValue: value });
    // 自动保存缓存
    saveCache();
  }
}

function updateNewItemManual(index: number, value: string) {
  if (index >= 0 && index < newItems.length) {
    const old = newItems[index];
    newItems.splice(index, 1, { ...old, manualValue: value });
    // 自动保存缓存
    saveCache();
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  // 先加载缓存，确保有初始数据
  loadCache();
  // 然后获取接口数据
  await getList();
  // 加载当前健康管家信息
  await loadCurrentButler();
});
watch(showInputPopup, (val) => {
  console.log('showInputPopup changed:', val);
});

// 加载当前选中的健康管家
const loadCurrentButler = async () => {
  try {
    // 优先从 demographicStore.currentInfo 中获取 healthId
    let butlerId = (demographicStore.currentInfo as any)?.healthId;
    
    // 如果没有，则从本地存储获取
    if (!butlerId) {
      const demographicInfo = localStg.get("demographicInfo");
      butlerId = demographicInfo?.healthId;
    }
    
    if (butlerId) {
      // 使用 demographicStore 的方法获取健康管家信息
      await demographicStore.getHealthButlerById(butlerId);
    }
  } catch (error) {
    console.error('加载健康管家信息失败:', error);
  }
};

// 显示健康管家列表
// const showManagerList = () => {
//   showManagerPopup.value = true;
//   // 加载管家列表
//   loadManagerList();
// };

// // 加载健康管家列表
// const loadManagerList = async () => {
//   try {
//     const res = await getHealthNurses();
//     console.log('获取健康管家列表:', res);
//     managerList.value = res.success?.records || [];
//   } catch (error) {
//     console.error('加载管家列表失败:', error);
//     managerList.value = [];
//     Taro.showToast({
//       title: '加载管家列表失败',
//       icon: 'none',
//       duration: 1500
//     });
//   }
// };

// // 选择健康管家
// const selectManager = async (manager: HealthManager) => {
//   try {
//     // 更新本地存储
//     localStg.set('currentButlerId', manager.id);
    
//     // 使用 demographicStore 的方法更新健康管家ID并自动获取详细信息
//     const success = await demographicStore.updateHealthButlerId(manager.id);
    
//     if (success) {
//       // 调用 API 保存更新后的数据
//       if (demographicStore.currentInfo) {
//         // 更新人口统计学信息中的健康管家ID
//         const obj = localStg.get("demographicInfo");
//         if (obj) {
//           obj.healthId = manager.id;
//           localStg.set("demographicInfo", obj);
//         }
//       }
      
//       showManagerPopup.value = false;
//       Taro.showToast({
//         title: `已选择${manager.name}作为健康管家`,
//         icon: 'success',
//         duration: 1500
//       });
//     } else {
//       Taro.showToast({
//         title: '切换失败',
//         icon: 'error',
//         duration: 1500
//       });
//     }
//   } catch (error) {
//     console.error('切换管家失败:', error);
//     Taro.showToast({
//       title: '切换失败',
//       icon: 'error',
//       duration: 1500
//     });
//   }
// };

// 判断是否为固定健康项目
// const isFixedHealthItem = (itemName: string) => {
//   const fixedItemNames = [
//     '血压心率',
//     '血氧',
//     '血糖',
//     '体温',
//     '血脂',
//     '尿酸',
//     '睡眠评分',
//     'BMI',
//     '体重',
//     '运动其他'
//   ];
//   return fixedItemNames.includes(itemName);
// };

// 关闭弹窗并重置状态
function closePopup() {
  showInputPopup.value = false;
  inputValue.value = "";
  newItemName.value = "";
  newItemIotValue.value = "";
  newItemManualValue.value = "";
  currentEditIndex.value = -1;
  isAddMode.value = false;
  nextTick(() => {
    showInputPopup.value = false;
  });
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  switch (status) {
    case "normal":
      return "green-txt";
    case "mild":
      return "yellow-txt";
    case "severe":
      return "red-txt";
    default:
      return "gray-txt";
  }
};
</script>

<style scoped>
.rotate-180 {
  transform: rotate(180deg);
  transition: transform 0.3s ease;
}
.green-txt {
  border: solid 1px #009900;
  color: #009900;
}
.yellow-txt {
  border: solid 1px #ff9900;
  color: #ff9900;
}
.red-txt {
  border: solid 1px #ff0000;
  color: #ff0000;
}
.gray-txt {
  border: solid 1px #999999;
  color: #999999;
}
</style>
